using FytSoa.Common.Extensions;
using FytSoa.Domain.Car;
using FytSoa.Domain.Cms;
using FytSoa.Domain.Sys;
using FytSoa.Sugar;
using MapsterMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace FytSoa.Application.App;

[ApiExplorerSettings(GroupName = "v5"),AllowAnonymous]
public class AppActivityService: IApplicationService
{
    private readonly SugarRepository<CarsActivity> _thisRepository;
    private readonly SugarRepository<SysAdvInfo> _advRepository;
    private readonly SugarRepository<SysCode> _codeRepository;
    private readonly SugarRepository<CarsActivityApply> _applyRepository;
    public AppActivityService(SugarRepository<CarsActivity> thisRepository
        ,SugarRepository<SysAdvInfo> advRepository
        ,SugarRepository<SysCode> codeRepository
        ,SugarRepository<CarsActivityApply> applyRepository)
    {
        _thisRepository = thisRepository;
        _advRepository = advRepository;
        _codeRepository = codeRepository;
        _applyRepository = applyRepository;
    }
    
    /// <summary>
    /// 查询活动
    /// </summary>
    /// <returns></returns>
    public async Task<CarsActivity> GetIndexAsync()
    {
       return  await _thisRepository.GetFirstAsync(m => m.Status && m.EndTime>DateTime.Now);
    }
    
    /// <summary>
    /// 返回广告位图及所在分会
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> GetBanaerAsync()
    {
        var adv = await _advRepository.GetFirstAsync(m => m.ColumnId ==1575677162965569536);
        var carType = await _codeRepository.GetListAsync(m => m.TypeId == 1575679160779673600);
        return new
        {
            AdvInfo = adv?.ImgUrl,
            Codes = carType?.Select(m=>m.Name)
        };
    }
    
    /// <summary>
    /// 添加活动
    /// </summary>
    /// <returns></returns>
    public async Task AddApplyAsync(CarsActivityApply param)
    {
        // 判断是否参加过活动
        var isExist =
            await _applyRepository.IsAnyAsync(m => m.ActivityId == param.ActivityId && m.UserId == param.UserId);
        if (isExist)
        {
            throw new BusinessException("您已参加过当前活动，无需重复报名~");
        }
        await _applyRepository.InsertAsync(param);
    }

    /// <summary>
    /// 查询用户是否报名参加活动
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<int> GetAppleByUser(long id)
    {
        return await _applyRepository.CountAsync(m=>m.UserId==id);
    }
}